#include "StdAfx.h"

Texture* IconButton::mHoverTexture = NULL;

IconButton::IconButton(const std::string& iconFile) : mIsHovered(false)
{
	if(mHoverTexture == NULL)
		mHoverTexture = sTexture.GetTexture("Interface\\BUTTONS\\UI-Quickslot-Depress.blp");
	mIconTexture = sTexture.GetTexture(iconFile);
	if(mIconTexture == NULL || mHoverTexture == NULL)
	{
		StartupException e =
		{
			"Missing file",
			"Unable to load a required icon for a button!",
		};

		throw e;
	}

	mPosX = mPosY = 0;
	mSize = 50;

	ReloadVertices();
}

void IconButton::ReloadVertices()
{
	mVertices[0].x = mPosX;
	mVertices[1].x = mPosX + mSize;
	mVertices[2].x = mPosX + mSize;
	mVertices[3].x = mPosX;

	mVertices[0].y = mPosY;
	mVertices[1].y = mPosY;
	mVertices[2].y = mPosY + mSize;
	mVertices[3].y = mPosY + mSize;

	mVertices[0].u = mVertices[3].u = 0.0f;
	mVertices[1].u = mVertices[2].u = 1.0f;

	mVertices[0].v = mVertices[1].v = 0.0f;
	mVertices[2].v = mVertices[3].v = 1.0f;
}

void IconButton::Draw()
{
	sD3D->SetTexture(0, *mIconTexture);
	sD3D->SetFVF(Vertex3FRHWT::FVF);
	sD3D->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, mVertices, sizeof(Vertex3FRHWT));
	sD3D->SetTexture(0, NULL);
	if(mIsHovered)
	{
		sD3D->SetTexture(0, *mHoverTexture);
		sD3D->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, mVertices, sizeof(Vertex3FRHWT));
		sD3D->SetTexture(0, NULL);

		sTooltipMgr.SetTooltip(mToolTip);
	}
	else
		sTooltipMgr.UnsetTooltip(mToolTip);
}

void IconButton::OnMouseMove(ui32 x, ui32 y, bool leftDown, bool rightDown)
{
	mIsHovered = (x >= mPosX && x <= (mPosX + mSize) && y >= mPosY && y <= (mPosY + mSize));
}

void IconButton::MouseActivity(bool left, Vertex2F pos, bool up)
{
	ui32 x = pos.x;
	ui32 y = pos.y;

	bool mHit = (x >= mPosX && x <= (mPosX + mSize) && y >= mPosY && y <= (mPosY + mSize));
	if(mHit == false)
		m_state = 0;
	else
	{
		if(up == false)
			m_state = 1;
		else
		{
			if(m_state == 1)
				OnMouseClick();

			m_state = 0;
		}
	}
}